﻿using System;
using System.Linq;
using EP.Base.BaseService.Manager.Config.Enum;
using EP.Base.BaseService.Manager.Interface;
using EP.Base.BaseService.Manager.Interface.Business;
using EP.Base.BaseService.Manager.Interface.Common;
using EP.Base.BaseService.Manager.Interface.Data;
using EP.Base.BaseService.Manager.Model;
using EP.Base.BaseService.Manager.Model.Entity;

namespace EP.Base.BaseService.Manager.Business.Task
{
    /// <summary>
    /// es备份删除任务--删除过程中如果有其它备份任务在使用要删除的备份会删除失败。
    /// </summary>
    public class IndexBackupDeleteTask:IEsIndexHandelTask
    {
        private readonly IEsClusters _esClusters;
        private readonly IIndexConfigs _indexConfigs;
        private readonly IEsData _esData;
        private readonly ILog _log;
        private readonly IIndexBackupLogs _indexBackupLogs;
        private readonly IJson _json;

        public IndexBackupDeleteTask(IEsClusters esClusters, IIndexConfigs indexConfigs, IEsData esData, ILog log, IIndexBackupLogs indexBackupLogs, IJson json)
        {
            _esClusters = esClusters;
            _indexConfigs = indexConfigs;
            _esData = esData;
            _log = log;
            _indexBackupLogs = indexBackupLogs;
            _json = json;
        }

        public bool Exec(EsTaskConfig taskConfig)
        {
            _log.Debug("执行索引备份删除服务 id=" + taskConfig.Id);

            //index信息
            var indexConfig = _indexConfigs.Get(taskConfig.IndexConfigId);
            if (indexConfig == null)
            {
                _log.WarnFormat("IndexConfigId={0},未找到对应的indexConfig数据！", taskConfig.IndexConfigId);
                return false;
            }
            //es集群信息
            var esClustersInfo = _esClusters.Get(indexConfig.ClusterId);
            if (esClustersInfo == null)
            {
                _log.WarnFormat("ClusterId={0},未找到对应的esClustersInfo数据！", indexConfig.ClusterId);
                return false;
            }
            //任务配置
            var currentTaskConfig = _json.DeserializeObject<IndexBackupDeleteTaskConfig>(taskConfig.Configs);
            
            DeleteBkFailLog(taskConfig.IndexConfigId,esClustersInfo.ServiceHostArr);
            
            //成功的备份
            var baklogs = _indexBackupLogs.GetIndexBackupLogsByIndexConfidId(taskConfig.IndexConfigId,(short)EnumIndexBackupLogState.Success);

            if (baklogs == null)
                return true;

            if (baklogs.Count <= currentTaskConfig.RetainNewestBkNum)
                return true;
            //删除不需要保留的备份
            foreach (var indexBackupLog in baklogs.OrderByDescending(n => n.Id).Skip(currentTaskConfig.RetainNewestBkNum))
            {
                var result= _esData.DeleteSnapshot(esClustersInfo.ServiceHostArr, indexBackupLog.Repository,
                    indexBackupLog.SnapshotName);
                if (result)
                    _indexBackupLogs.UpdateStateAndDeleteTimeById(indexBackupLog.Id,
                        (short) EnumIndexBackupLogState.Deleted, DateTime.Now);
            }
            return true;
        }

        private void DeleteBkFailLog(int indexConfigId, string[] serviceHostArr)
        {
            System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                //失败的备份
                var baklogs = _indexBackupLogs.GetIndexBackupLogsByIndexConfidId(indexConfigId, (short)EnumIndexBackupLogState.BkFail);
                if (baklogs == null)
                    return ;
                //删除失败的备份
                foreach (var indexBackupLog in baklogs)
                {
                    var result = _esData.DeleteSnapshot(serviceHostArr, indexBackupLog.Repository,
                        indexBackupLog.SnapshotName);
                    if (result)
                        _indexBackupLogs.UpdateStateAndDeleteTimeById(indexBackupLog.Id,(short)EnumIndexBackupLogState.Deleted, DateTime.Now);
                }
            });
        }
    }
}
